package com.ljr.factory.data.helper;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.ljr.common.factory.data.DataSource;
import com.ljr.factory.Factory;

import com.ljr.factory.R;
import com.ljr.factory.model.db.User;
import com.ljr.factory.model.db.User_Table;
import com.ljr.factory.net.NetWork;
import com.ljr.factory.net.RemoteService;
import com.ljr.factory.persistence.Account;
import com.ljr.factory.model.api.RspModel;
import com.ljr.factory.model.api.account.AccountRspModel;
import com.ljr.factory.model.api.account.LoginModel;
import com.ljr.factory.model.api.account.RegisterModel;
import com.raizlabs.android.dbflow.sql.language.CursorResult;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.database.transaction.QueryTransaction;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 林佳荣 on 2018/4/24.
 * Github：https://github.com/ljrRookie
 * Function ：
 */

public class AccountHelper {
    /**
     * 注册的接口，异步的调用
     * @param model
     * @param callback
     */
    public static void register(final RegisterModel model, final DataSource.Callback<User> callback) {
        //调用Retrofit对我们的网络请求接口做代理
        RemoteService service = NetWork.remote();
        Call<RspModel<AccountRspModel>> call = service.accountRegister(model);
        //异步请求
        call.enqueue(new AccountRspCallback(callback));


    }
    /**
     * 登录的调用
     *
     * @param model    登录的Model
     * @param callback 成功与失败的接口回送
     */
    public static void login(final LoginModel model, final DataSource.Callback<User> callback) {
        // 调用Retrofit对我们的网络请求接口做代理
        RemoteService service = NetWork.remote();
        // 得到一个Call
        Call<RspModel<AccountRspModel>> call = service.accountLogin(model);
        // 异步的请求
        call.enqueue(new AccountRspCallback(callback));

    }
    /**
     * 对设备Id进行绑定的操作
     *
     * @param callback Callback
     */
    public static void bindPush(final DataSource.Callback<User> callback) {
        // 检查是否为空
        String pushId = Account.getPushId();
        if (TextUtils.isEmpty(pushId))
            return;

        // 调用Retrofit对我们的网络请求接口做代理
        RemoteService service = NetWork.remote();
        Call<RspModel<AccountRspModel>> call = service.accountBind(pushId);
        call.enqueue(new AccountRspCallback(callback));
    }
    /**
     * 请求的回调部分
     */
    private static class AccountRspCallback implements Callback<RspModel<AccountRspModel>> {
        final DataSource.Callback<User> mCallback;

        public AccountRspCallback(DataSource.Callback<User> callback) {
            this.mCallback = callback;
        }

        @Override
        public void onResponse(Call<RspModel<AccountRspModel>> call, Response<RspModel<AccountRspModel>> response) {
            //请求成功返回
            //从返回中得到我们的全局Model，内部是使用的Gson进行解析
            RspModel<AccountRspModel> rspModel = response.body();
            if (rspModel.success()) {
                //拿到实体
                AccountRspModel accountRspModel = rspModel.getResult();
                //获取我的信息
                final User user = accountRspModel.getUser();
                DbHelper.save(User.class, user);
                /**
                 * 保存数据
                 */
                //第一种
                // user.save();
                //第二种和第一种一样
                // FlowManager.getModelAdapter(User.class).save(user);
                // 第三种，事务中
               /* DatabaseDefinition definition = FlowManager.getDatabase(AppDatabase.class);
                definition.beginTransactionAsync(new ITransaction() {
                    @Override
                    public void execute(DatabaseWrapper databaseWrapper) {
                        FlowManager.getModelAdapter(User.class)
                                .save(user);
                    }
                }).build().execute();*/
                // 同步到XML持久化中
                Account.login(accountRspModel);
                //判断绑定状态，是否绑定设备
                if(accountRspModel.isBind()){
                    //设置绑定状态为True
                    Account.setBind(true);
                    //然后返回
                    if(mCallback != null )
                        mCallback.onDataLoaded(user);
                } else{
                    // 进行绑定的唤起
                    bindPush(mCallback);
                }
            }else{
                Factory.decodeRspCode(rspModel,mCallback);
            }
        }

        @Override
        public void onFailure(Call<RspModel<AccountRspModel>> call, Throwable t) {
            // 网络请求失败
            if (mCallback != null)
                mCallback.onDataNotAvailable(R.string.data_network_error);
        }
    }
}
